/*
* Copyright 2011 Stepan Riha
*
* This file may be used under the terms of of the
* GNU General Public License Version 3 or later (the "GPL"),
* http://www.gnu.org/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {

  	var response = {};
  	
	// Show the extension Options page  	
  	if(request.action == "showOptions") {
  		chrome.tabs.create({
			index: sender.tab.index + 1,
			url: chrome.extension.getURL("html/options.html") 
		});
  	}
  	
  	// Retrieve and return availability information from a site
  	if(request.action == "getBookInfo") {
  		var isbn = request.isbn;
  		BB.getSite(request.site, function(site) {
			var tab_id = sender.tab.id;
			
			var url = site.query_url(isbn);
			jQuery.ajax({
	
				url: url,
	
				success: function(data, textStatus, jqXHR) {
					var answer = site.process(jqXHR, isbn) || '';
					chrome.tabs.sendRequest(tab_id, {
							action: "setBookInfo",
							site: request.site,
							text: answer
						});
				},
	
				error: function(jqXHR, textStatus, errorThrown) {
					chrome.tabs.sendRequest(tab_id, {
							action: "setBookInfo",
							site: request.site,
							text: textStatus,
							error: true
						});
				}
			});
		});
  	}
  
  	// Return the list of active sites
    if (request.action == "getAlternatives") {
    	response = {
    		sites: []
    	};
    	
    	var stores = BB.get_active_stores();
    	var isbn = request.isbn;
    	
    	// Collect stores
		for(var i = 0; i < stores.length; i++) {
			var site = stores[i];
			if(site.active) {
				response.sites.push({
					kind: site.kind,
					title: site.title,
					name: site.name,
					id: site.id,
					link: site.url(isbn)
				});
			}
		}

		BB.process_active_libraries(function(libraries) {
			// Collect libraries
			for(var i = 0; i < libraries.length; i++) {
				var site = libraries[i];
				if(site.active) {
					response.sites.push({
						kind: site.kind,
						title: site.title,
						name: site.name,
						id: site.id,
						link: site.url(isbn)
					});
				}
			}
			sendResponse(response);
		});
    } else {
		sendResponse(response);
	}

});
